import { defineStore } from 'pinia'
import { movieService } from '../services/api'

export const useMovieStore = defineStore('movie', {
  state: () => ({
    movies: [],
    currentMovie: null,
    seats: [],
    loading: false,
    error: null
  }),

  actions: {
    async fetchMovies() {
      this.loading = true
      this.error = null
      try {
        this.movies = await movieService.getAllMovies()
      } catch (error) {
        this.error = '获取电影列表失败：' + error.message
        console.error('Error fetching movies:', error)
      } finally {
        this.loading = false
      }
    },

    async fetchMovie(id) {
      this.loading = true
      this.error = null
      try {
        this.currentMovie = await movieService.getMovie(id)
      } catch (error) {
        this.error = '获取电影详情失败：' + error.message
        console.error('Error fetching movie:', error)
      } finally {
        this.loading = false
      }
    },

    async fetchSeats(movieId) {
      this.loading = true
      this.error = null
      try {
        const data = await movieService.getSeats(movieId)
        this.seats = data.seatflag
      } catch (error) {
        this.error = '获取座位信息失败：' + error.message
        console.error('Error fetching seats:', error)
      } finally {
        this.loading = false
      }
    },

    async purchaseTicket(movieId, seatNumber, buyerName) {
      this.loading = true
      this.error = null
      try {
        const ticket = await movieService.buyTicket(movieId, seatNumber, buyerName)
        await this.fetchSeats(movieId)
        return ticket
      } catch (error) {
        // 添加调试信息
        console.log('原始错误信息:', error.message)
        const friendlyError = this.getFriendlyErrorMessage(error)
        this.error = '购票失败：' + friendlyError
        throw new Error(friendlyError)
      } finally {
        this.loading = false
      }
    },

    async purchaseTicketsBatch(movieId, seatNumbers, buyerName) {
      this.loading = true
      this.error = null
      try {
        const tickets = await movieService.buyTicketsBatch(movieId, seatNumbers, buyerName)
        await this.fetchSeats(movieId)
        return tickets
      } catch (error) {
        // 添加调试信息
        console.log('原始错误信息:', error.message)
        const friendlyError = this.getFriendlyErrorMessage(error)
        this.error = '购票失败：' + friendlyError
        throw new Error(friendlyError)
      } finally {
        this.loading = false
      }
    },

    getFriendlyErrorMessage(error) {
      const errorMessage = error.message || error.toString()
      console.log('错误消息内容:', errorMessage) // 调试用
      
      // 更宽松的匹配逻辑
      if (errorMessage.includes('5张票') || errorMessage.includes('5张') || errorMessage.includes('最多只能购买')) {
        if (errorMessage.includes('已购买') && errorMessage.includes('张')) {
          return errorMessage // 保持原有的详细提示
        }
        return '每人每场电影最多只能购买5张票'
      }
      
      if (errorMessage.includes('座位已被占用') || errorMessage.includes('已被占用') || errorMessage.includes('占用')) {
        return '您选择的座位已被其他人购买，请选择其他座位'
      }
      
      if (errorMessage.includes('电影不存在') || errorMessage.includes('不存在')) {
        return '电影信息不存在，请刷新页面重试'
      }
      
      if (errorMessage.includes('一次最多只能购买') || errorMessage.includes('最多只能购买')) {
        return '一次最多只能选择5个座位'
      }
      
      if (errorMessage.includes('请选择座位')) {
        return '请先选择座位'
      }
      
      // 如果还是匹配不到，返回原始错误信息供调试
      return errorMessage || '系统繁忙，请稍后重试'
    },

    clearError() {
      this.error = null
    }
  }
})